import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tooltip, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { MSGraphClientFactory } from '@microsoft/sp-http';

// 定义老板邮箱地址列表
// const BOSS_EMAIL_ADDRESSES = [
//   'boss@yourcompany.com', // 替换为实际的老板邮箱地址
//   'manager@yourcompany.com'
// ];

const BossCalledMe = (props) => {
  console.log('BossCalledMe props:', props);
  const { context } = props;
  const [timeRange, setTimeRange] = useState('past-week');
  const [bossEmails, setBossEmails] = useState([]);
  const [loading, setLoading] = useState(false);
  const [emailStats, setEmailStats] = useState({
    totalEmails: 0,
    daysCount: 0,
    fromManager: 0,
    totalReplied: 0,
    repliedToday: 0
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取老板邮件数据
  const fetchBossEmails = async () => {
    setLoading(true);
    setBossEmails([]);
    setEmailStats({
      totalEmails: 0,
      daysCount: 0,
      fromManager: 0,
      totalReplied: 0,
      repliedToday: 0
    });

    try {
      if (!context || !context.msGraphClientFactory) {
        console.error('SharePoint context或MSGraphClientFactory未定义');
        message.error('无法获取SharePoint context或Graph客户端工厂');
        setLoading(false);
        return;
      }

      // 使用 MSGraphClientFactory 获取 Graph 客户端
      const graphClient = await context.msGraphClientFactory.getClient();

      // **步骤1: 获取当前用户的经理信息**
      let managerEmail = null;
      try {
          const managerResponse = await graphClient.api('/me/manager').select('mail').get();
          console.log('获取的经理信息:', managerResponse);
          if (managerResponse && managerResponse.mail) {
              managerEmail = managerResponse.mail;
              console.log('获取到经理邮箱:', managerEmail);
          } else {
              console.log('未获取到经理信息或经理没有邮箱。');
          }
      } catch (managerError) {
          console.error('获取经理信息时出错:', managerError);
          // 这里的错误可能是用户没有设置经理，或者 Graph API 调用失败
      }

      // **步骤4: 处理用户没有经理的情况**
      if (!managerEmail) {
          console.log('用户未创建企业组织关系或经理没有邮箱，不进行邮件查询。');
          message.info('您未创建企业组织关系'); // 显示提示信息
          setLoading(false);
          return;
      }

      // 根据时间范围设置筛选条件
      let dateFilter = '';
      const now = new Date();
      const todayStart = new Date(now);
      todayStart.setHours(0, 0, 0, 0); // 今天的开始时间

      switch(timeRange) {
        case 'past-week':
          const pastWeekStart = new Date(todayStart);
          pastWeekStart.setDate(todayStart.getDate() - 7);
          dateFilter = `receivedDateTime ge ${pastWeekStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
          break;
        case 'next-two-weeks': // 过去14天的邮件
          const pastTwoWeeksStart = new Date(todayStart);
          pastTwoWeeksStart.setDate(todayStart.getDate() - 14);
          dateFilter = `receivedDateTime ge ${pastTwoWeeksStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
          break;
        case 'next-four-weeks': // 过去28天的邮件
          const pastFourWeeksStart = new Date(todayStart);
          pastFourWeeksStart.setDate(todayStart.getDate() - 28);
          dateFilter = `receivedDateTime ge ${pastFourWeeksStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
          break;
        default: // 默认过去一周
          const defaultPastWeekStart = new Date(todayStart);
          defaultPastWeekStart.setDate(todayStart.getDate() - 7);
          dateFilter = `receivedDateTime ge ${defaultPastWeekStart.toISOString()} and receivedDateTime le ${now.toISOString()}`;
          break;
      }

      // **步骤3: 在邮件查询中加入经理邮箱过滤条件**
      const finalFilter = `${dateFilter} and from/emailAddress/address eq '${managerEmail}'`;
      console.log('最终的邮件过滤条件:', finalFilter);

      // 调用 Microsoft Graph API 获取邮件
      const response = await graphClient
        .api(`/me/messages`)
        .filter(finalFilter) // 使用包含经理邮箱的过滤条件
        .top(100)
        .orderby('receivedDateTime desc')
        .get();

      console.log('获取的老板邮件数据:', response);

      // 处理邮件数据
      const processedEmails = response.value.map(email => {
        // 处理回复状态
        const processedStatus = {
          text: email.isRead ? '已处理' : '待处理',
          type: email.isRead ? 'processed' : 'pending-process'
        };

        // 处理回复时间
        const processedTime = email.isRead ? new Date(email.lastModifiedDateTime).toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          weekday: 'short',
          hour: '2-digit',
          minute: '2-digit'
        }) : '-';

        return {
          key: email.id,
          id: email.id,
          sender: email.from?.emailAddress?.name || '未知发件人',
          sendTime: new Date(email.receivedDateTime).toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            weekday: 'short',
            hour: '2-digit',
            minute: '2-digit'
          }),
          subject: email.subject || '(无主题)',
          priority: {
            text: email.importance === 'high' ? '高' : email.importance === 'low' ? '低' : '普通',
            type: email.importance === 'high' ? 'high' : email.importance === 'low' ? 'low' : 'normal'
          },
          replyStatus: processedStatus,
          replyTime: processedTime,
          emailType: '老板邮件'
        };
      });

      setBossEmails(processedEmails);

      // 计算邮件统计数据
      const calculatedStats = {
        totalEmails: processedEmails.length,
        daysCount: timeRange === 'past-week' ? 7 : timeRange === 'next-two-weeks' ? 14 : 28,
        // fromManager: processedEmails.filter(email => {
        //   const senderEmail = email.from?.emailAddress?.address || '';
        //   return BOSS_EMAIL_ADDRESSES.includes(senderEmail.toLowerCase());
        // }).length,
        fromManager: processedEmails.length, // 现在所有获取到的邮件都来自经理，所以直接使用总数
        totalReplied: processedEmails.filter(email => email.replyStatus.type === 'processed').length,
        repliedToday: processedEmails.filter(email => {
          const processed = email.replyStatus.type === 'processed';
          if (!processed) return false;
          const processDate = new Date(email.replyTime !== '-' ? email.replyTime : email.sendTime);
          const today = new Date();
          return processDate.getDate() === today.getDate() &&
                 processDate.getMonth() === today.getMonth() &&
                 processDate.getFullYear() === today.getFullYear();
        }).length
      };

      setEmailStats(calculatedStats);

    } catch (error) {
      console.error('获取邮件数据时出错:', error);
      message.error('获取邮件数据失败，请稍后重试');
      setBossEmails([]);
      setEmailStats({
        totalEmails: 0,
        daysCount: 0,
        fromManager: 0,
        totalReplied: 0,
        repliedToday: 0
      });
    } finally {
      setLoading(false);
    }
  };

  // 当时间范围或context变化时获取邮件数据
  useEffect(() => {
    if (context) {
      fetchBossEmails();
    }
  }, [timeRange, context]);

  // Handle table pagination, sorting, and filtering changes
  const handleTableChange = (pagination, filters, sorter) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
    // Note: Sorting and filtering logic can be added here if needed in the future
  };

  // 获取邮件数量
  const getEmailCount = () => {
    return bossEmails.length;
  };

  // 表格列定义
  const columns = [
    { title: '序号', dataIndex: 'id', key: 'id', width: '5%', render: (text, record, index) => index + 1 },
    { title: '发件人姓名', dataIndex: 'sender', key: 'sender', width: '10%', },
    { title: '发送时间', dataIndex: 'sendTime', key: 'sendTime', width: '12%', },
    { title: '主题', dataIndex: 'subject', key: 'subject', width: '22%', ellipsis: { showTitle: false, }, render: subject => (<Tooltip placement="topLeft" title={subject}><span>{subject}</span></Tooltip>), },
    { title: '优先级', dataIndex: 'priority', key: 'priority', width: '8%', render: (priority) => (<span className={`priority-badge ${priority.type === 'high' ? 'priority-high' : 'priority-low'}`}>{priority.text}</span>), },
    { title: '处理状态', dataIndex: 'replyStatus', key: 'replyStatus', width: '10%', render: (status) => (<span className={`reply-status ${status.type === 'processed' ? 'status-processed' : 'status-pending-process'}`}>{status.text}</span>), },
    { title: '处理时间', dataIndex: 'replyTime', key: 'replyTime', width: '12%', },
    { title: '邮件类型', dataIndex: 'emailType', key: 'emailType', width: '10%', },
  ];

  // 设置行样式
  const getRowClassName = (record, index) => {
    return index % 2 === 1 ? 'light-blue-row' : '';
  };

  return (
    <div className="email-container">
      <style jsx="true">
        {`
          .email-container { padding: 20px; }
          .light-blue-row { background-color: #f0f8ff; }
          .ant-table-tbody > tr.light-blue-row:hover > td { background-color: #e6f4ff; }
          .page-title { margin: 0 0 10px 0; }
          .email-info { margin: 10px 0; }
          .description { color: #666; margin: 5px 0 15px 0; }
          .emoji { font-size: 16px; margin-right: 5px; }
          .button-container { display: flex; justify-content: flex-end; margin-bottom: 15px; }
          .email-count { color: #1890ff; font-size: 18px; font-weight: bold; }
          .stat-number { color: #1890ff; font-weight: bold; }
          .header-section { margin-bottom: 20px; }
          .table-container { background-color: #fff; width: 100%; }
          .hover-content { cursor: pointer; }
          .priority-badge { cursor: pointer; }
          .reply-status { cursor: pointer; }
          .priority-high { color: #faad14; }
          .priority-low { color: #1890ff; }
          .status-processed { color: #52c41a; }
          .status-pending-process { color: #f5222d; }
          .ant-table-container { width: 100%; }
          .ant-table { width: 100%; }
          .ant-table-cell { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
          .ant-table-wrapper { width: 100%; }
        `}
      </style>

      <style global jsx>
        {`
          .ant-tooltip-inner { background-color: white; color: black; border: 1px solid #e8e8e8; }
          .ant-tooltip-arrow-content { background-color: white; border: 1px solid #e8e8e8; }
        `}
      </style>

      <div className="header-section">
        <h2 className="page-title">老板邮件</h2>
        <p className="email-info">
          {timeRange === 'past-week' ? '过去一周' : timeRange === 'next-two-weeks' ? '过去两周' : '过去四周'}您一共收到
          <span className="email-count"> {getEmailCount()} </span> 封老板邮件
        </p>
        <p className="description">
          请及时处理老板邮件！<span className="emoji">👨‍💼</span>
        </p>
        
        <div className="button-container">
          <Space>
            <Button 
              type={timeRange === 'past-week' ? 'primary' : 'default'} 
              ghost={timeRange === 'past-week'}
              onClick={() => setTimeRange('past-week')}
            >
              过去一周
            </Button>
            <Button 
              type={timeRange === 'next-two-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-two-weeks'}
              onClick={() => setTimeRange('next-two-weeks')}
            >
              过去两周
            </Button>
            <Button 
              type={timeRange === 'next-four-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-four-weeks'}
              onClick={() => setTimeRange('next-four-weeks')}
            >
              过去四周
            </Button>
          </Space>
        </div>
      </div>

      <Table
        dataSource={bossEmails.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
        columns={columns}
        loading={loading}
        rowClassName={getRowClassName}
        className="table-container"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: bossEmails.length,
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'],
        }}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default BossCalledMe;